package ua.kharkov.knure.dereza.summarytask4.command;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import ua.kharkov.knure.dereza.summarytask4.core.Constants;
import ua.kharkov.knure.dereza.summarytask4.db.bean.ClientBean;
import ua.kharkov.knure.dereza.summarytask4.db.dao.CardDAO;
import ua.kharkov.knure.dereza.summarytask4.db.dao.DAOFactory;
import ua.kharkov.knure.dereza.summarytask4.db.dao.StatusDAO;
import ua.kharkov.knure.dereza.summarytask4.db.dao.mysql.MysqlDAOFactory;
import ua.kharkov.knure.dereza.summarytask4.db.dto.StatusDTO;

/**
 * Unlock card command.
 * 
 * @author dereza
 * 
 */
public class UnlockCardCommand extends Command {

	private static final long serialVersionUID = -6244086871143335619L;

	private static final Logger log = Logger.getLogger(UnlockCardCommand.class);

	@Override
	public String execute(HttpServletRequest req, HttpServletResponse res) {
		log.debug("Command started");

		// gets client's session
		HttpSession session = req.getSession(false);

		// gets ClientBean from session
		ClientBean clientBean = (ClientBean) session.getAttribute("clientbean");
		log.trace("Got clientbean  from session --> " + clientBean);

		// if clientBean == null forward to login page
		if (clientBean == null) {
			String forward = Constants.COMMAND_LOGOUT;
			return forward;
		}

		// gets cards id from request
		String[] cardIds = req.getParameterValues("id");

		// if any card weren't chosen for unlocking
		// will return forward with link to admin card list
		String forward = Constants.COMMAND_ADMIN_LIST_CARDS;
		if (cardIds == null) {
			return forward;
		}

		List<Integer> listId = new ArrayList<Integer>();
		for (String id : cardIds) {
			listId.add(Integer.valueOf(id));
		}
		log.trace("got cards id --> " + listId);

		// creates the required DAO generator
		MysqlDAOFactory mysqlFactory = (MysqlDAOFactory) DAOFactory
				.getDAOFactory(DAOFactory.MYSQL);

		// / creates DAO for card
		CardDAO cardDAO = mysqlFactory.getCardDAO();

		// gets status dao
		StatusDAO statusDAO = mysqlFactory.getStatusDAO();
		StatusDTO statusDTO = statusDAO
				.findStatusByName(Constants.STATUS_UNLOCKED);
		int statusId = statusDTO.getId();

		// execute unlocking
		cardDAO.updateStatuses(listId, statusId);
		log.info("Cards was unlocked --> " + listId);
		log.debug("Command finished");
		return forward;
	}

	@Override
	public String toString() {
		return "UnlockCardCommand";
	}
}